/**
    @file
    Program for solving quadratic equation.

    @author Dmitry Kharlamov, student of 1st course DREC MIPT.
    @version 1.2
*/


#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <float.h>



const double POISON =  -13.666;
const int N_COEFF   =   3;
const int N_ROOTS   =   2;
const int INF_ROOTS =  -1;


/**
    Function quadratic solves quadratic equation(ax^2 + bx + c = 0)
    @param coef  array of 3 coefficients (a, b, c)
    @param roots array for 2 roots(x1, x2)
    @return count of roots(-1 then infinite root)

*/
int quadratic(double coef[], double roots[]);


int main()
{

    double coefficients[N_COEFF] = {POISON, POISON, POISON};
    double roots[N_ROOTS] = {POISON, POISON};

    printf("This program solves quadratic equation.");
    printf("Write coefficients of quadratic equation(e.g a = 123 b = 321 c = 0.1)\n");
    while (scanf("a = %lg b = %lg c = %lg", &coefficients[0], &coefficients[1], &coefficients[2]) != 3)
    {

        while (getchar() != '\n');
        printf("Write correct!(e.g a = 123 b = -321 c = 0.1)\n");
    }


    int count_roots = quadratic(coefficients, roots);

    switch(count_roots)
    {

        case INF_ROOTS:
            printf("All real numbers");
            break;
        case 0:
            printf("No roots");
            break;
        case 1:
            printf("Count of roots: %d\nx = %lg", count_roots, roots[0]);
            break;
        case 2:
            printf("Count of roots: %d\nx1 = %lg x2 = %lg", count_roots, roots[0], roots[1]);
            break;

    }

    return 0;
}


int quadratic(double coef[], double roots[])
{
    assert(coef != NULL);
    assert(roots != NULL);
    if (abs(coef[0]) <= DBL_EPSILON)
    {
        if (abs(coef[1]) <= DBL_EPSILON)
        {
            if (abs(coef[2]) <= DBL_EPSILON)
                return INF_ROOTS;
            else
                return 0;

        }
        else // coef[1] != 0
        {
            roots[0] = - coef[2]/coef[1];
            return 1;
        }
    }

    else // coef[0] != 0
    {
        double discr = coef[1]*coef[1] - 4*coef[0]*coef[2];
        if (discr < 0)
            return 0;
        else
        {
            if (discr == 0)
            {
                roots[0] = - coef[1] / 2/coef[2];
                return 1;
            }
            else
            {
                discr = sqrt(discr);
                roots[0] = (- coef[1] + discr) / 2/coef[0];
                roots[1] = (- coef[1] - discr) / 2/coef[0];
                return 2;

            }

        }

    }
}
